
import axios from 'axios'
import baseUrl from './baseUrl';
import { Message } from 'element-ui';
// 创建 axios 实例

let service = axios.create({
 // headers: {'Authorization':localStorage.getItem('token')},
  timeout: 60000
})
service.defaults.baseURL = baseUrl
// 设置 post、put 默认 Content-Type
service.defaults.headers.post['Content-Type'] = 'application/json'
service.defaults.headers.put['Content-Type'] = 'application/json'

// 添加请求拦截器
service.interceptors.request.use(
  (config) => {
    if (localStorage.getItem('token')) {
      config.headers.Authorization = localStorage.getItem('token');
    }
    if (config.method === 'post' || config.method === 'put') {
      // post、put 提交时，将对象转换为string, 为处理Java后台解析问题
      config.data = JSON.stringify(config.data)
    }

    // 请求发送前进行处理
    return config
  },
  (error) => {
    // 请求错误处理
    return Promise.reject(error)
  }
)

// 添加响应拦截器
service.interceptors.response.use(
  (response) => {
    if (response.status === 200) {
      if (response.data && response.data.code == '222') {
         Message(response.data.msg);
        // localStorage.clear();
        // window.setTimeout(function () {
        //   router.push('/login');
        // }, 1000);
        // return;
      }
      if (response.data && response.data.code != '200') {
            if(response.data.code == 500){
                Message.error(response.data.message);
                //localStorage.clear();
                // window.setTimeout(function () {
                //   location.href='/#/login'
                // }, 1000);
                // return;

            }
            if(response.data.code == 401 ){
                Message.error(response.data.message);
                localStorage.clear();
                window.setTimeout(function () {
                    location.href='/docs/#/login'
                }, 1000);
                return;
            }
          if(response.data.code == 404 ){
              Message.error(response.data.message);
              // localStorage.clear();
              // window.setTimeout(function () {
              //   location.href='/#/login'
              // }, 1000);
              return;

          }

          return ;
        //Message(response.data.message);
        //window.alert(response.data.msg);
      }
      return response.data;

    }

  },
  (error) => {
    window.console.log(error);

  }
)

/**
 * 创建统一封装过的 axios 实例
 * @return {AxiosInstance}
 */
export default function () {
  return service
}
